package com.cjm.nio.demo;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class MainReactor implements Runnable {
    private Selector selector;
    private SubReactorThreadGroup subReactorThreadGroup;
    private static final int DEFAULT_IO_THREAD_COUNT = 4;
    private int ioThreadCount = DEFAULT_IO_THREAD_COUNT;
    public MainReactor(ServerSocketChannel ssc) {
        try {
            selector = Selector.open();
            ssc.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        subReactorThreadGroup = new SubReactorThreadGroup(ioThreadCount);
    }

    @Override
    public void run() {
        System.err.println("main reactor is running ...");
        while (!Thread.interrupted()) {
            Set<SelectionKey> ops = null;
            try {
                selector.select(1000);
                ops = selector.selectedKeys();
            } catch (IOException e) {
                e.printStackTrace();
            }

            for(Iterator<SelectionKey> it = ops.iterator();it.hasNext();) {
                SelectionKey key = it.next();
                it.remove();

                try {
                    if (key.isAcceptable()) {
                        System.err.println("收到客户端请求...");
                        ServerSocketChannel serverSc = (ServerSocketChannel) key.channel();
                        SocketChannel clientChannel = serverSc.accept();
                        clientChannel.configureBlocking(false);
                        subReactorThreadGroup.dispatch(clientChannel);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    System.err.println("客户端主动断开连接...");
                }


            }
        }
    }
}
